package com.meeting.aop;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.meeting.annotation.AuthCheck;
import com.meeting.entity.Customer;
import com.meeting.entity.User;
import com.meeting.exception.BusinessException;
import com.meeting.model.enums.UserRole;
import com.meeting.model.enums.UserStatusEnum;
import com.meeting.service.CustomerService;
import com.meeting.service.UserService;
import com.meeting.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    @Resource
    private CustomerService customerService;

    @Around("@annotation(authCheck)")
    public Object doIntercept(ProceedingJoinPoint pjp, AuthCheck authCheck) throws Throwable {
        UserRole roleEnum = authCheck.mustRole();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        System.out.println(token);
        Claims claims = JwtUtil.getClaimsFromToken(token);
        Integer role = claims.get("role", Integer.class);
        Long id = claims.get("id", Long.class);
        if (role == null) { // 没有role的是customer
            LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Customer::getId, id);
            Customer one = customerService.getOne(queryWrapper);
            if (one.getStatus() != UserStatusEnum.ACTIVE.getCode()) {
                throw new BusinessException(403, "账号封禁中");
            }
            return pjp.proceed();
        }
        // 查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, id);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            throw new BusinessException(403, "用户未登录");
        }
        if (user.getRole() != roleEnum.getCode()) {
            throw new BusinessException(403, "用户无权限");
        }
        if (user.getStatus() != UserStatusEnum.ACTIVE.getCode()) {
            throw new BusinessException(403, "账号封禁中");
        }
        return pjp.proceed();
    }
}
